/**
 * description:生产环境webpack配置文件
 * author:
 * date:2020/04/01
 * */
const webpackBase = require("./webpack.config.base");
const utils = require("./utils");
const config = require("./config");
const merge = require('webpack-merge');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");//提取css到单独文件的插件
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');//压缩css插件
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');

module.exports = merge(webpackBase, {
    module: {
        rules: [
            ...utils.generatorStyleLoaders({cssSourceMap: config.cssSourceMap, extract: true})
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: `[name]/css/[name].css`, // 类似output,[name]为entry key
            chunkFilename: `${config.toStaticPath}/css/[name].css`, // 为公共css包output路径
        }),
        new OptimizeCssAssetsPlugin(),
        /* 优化js */
        new ParallelUglifyPlugin({
            uglifyJS: {
                warnings: false, // 在UglifyJs删除没有用到的代码时不输出警告
                output: {
                    beautify: false, //不需要格式化
                    comments: true //不保留注释
                },
                compress: {
                    drop_console: true, // 删除所有的 `console` 语句，可以兼容ie浏览器
                    collapse_vars: true, // 内嵌定义了但是只用到一次的变量
                    reduce_vars: true // 提取出出现多次但是没有定义成变量去引用的静态值
                }
            }
        })
    ],
    //压缩js optimization.splitChunks
    optimization: {
        splitChunks: {
            chunks: 'all',
            cacheGroups: {
                // 公共模块抽离
                commonsJs: {
                    test: (module) => {
                        return !(/node_modules/.test(module.context));
                    },
                    minChunks: 2, //抽离公共代码时，这个代码块最小被引用的次数
                    minSize: 0, // This is example is too small to create commons chunks
                    priority: 1
                },
                // 第三方包抽离
                vendors: {
                    test: (module) => {
                        return /node_modules/.test(module.context);
                    },
                    minChunks: 2,
                    priority: 10
                },
                // MiniCssExtractPlugin提取出来的css利用splitChunks抽取公共部分
                styles: {
                    test: /\.css$/,
                    chunks: 'all',
                    enforce: true,
                    priority: 20,
                }
            }
        }
    }
});
